package edu.uoc.tds.pec4.vista;

import edu.uoc.tds.pec4.excepciones.FechasIncongruentesException;
import edu.uoc.tds.pec4.gestor.GestorEvento;
import edu.uoc.tds.pec4.gestor.impl.GestorEventoImpl;
import edu.uoc.tds.pec4.model.SS1_CentroDocente;
import edu.uoc.tds.pec4.model.SS2_Evento;
import edu.uoc.tds.pec4.util.ComponentsUtils;
import edu.uoc.tds.pec4.util.ExceptionUtils;
import edu.uoc.tds.pec4.util.KeyValue;
import edu.uoc.tds.pec4.util.LanguageUtils;
import java.awt.BorderLayout;
import java.lang.String;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.table.DefaultTableModel;

/**
 * Tecnicas de Desarrollo de Software - (UOC)
 * Clase para representar cancelar un evento en el sistema.
 * @author Grupo Magicsoftware - Yolanda Jiménez Anaya
 * @version 1.0
 */

public class SS2_PantallaCancelarEvento extends javax.swing.JPanel {

    public GestorEvento objetoRemoto;
    private SS2_PantallaAltaEvento sS2_PanelAltaEvento;

    /** Creates new form Prueba */
    public SS2_PantallaCancelarEvento(GestorEvento objetoRemoto) {
        this.objetoRemoto = objetoRemoto;
        initComponents();
        //intialCharge();
        jComboBoxCentro.setSelectedItem(jComboBoxCentro);
        setListCentrosToCombo(jComboBoxCentro);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelInicio = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jSeparator1 = new javax.swing.JSeparator();
        ButtonBuscar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxCentro = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        FechaHasta = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        FechaDesde = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        jButtonCancel = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)},
                {null, null, null, null, null, new Boolean(true)}
            },
            new String [] {
                "Fecha", "Codigo", "Evento", "Centro", "Duracion", "Cancelar"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        ButtonBuscar.setText("Buscar");
        ButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonBuscarActionPerformed(evt);
            }
        });

        jLabel1.setText("Centro");

        jComboBoxCentro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxCentroActionPerformed(evt);
            }
        });

        jLabel3.setText("Fecha Hasta:");

        jLabel2.setText("Fecha Desde:");

        FechaDesde.setText("");

        jLabel4.setText("Filtro:");

        jButtonCancel.setText("Cancelar");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelInicioLayout = new javax.swing.GroupLayout(jPanelInicio);
        jPanelInicio.setLayout(jPanelInicioLayout);
        jPanelInicioLayout.setHorizontalGroup(
            jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelInicioLayout.createSequentialGroup()
                .addGroup(jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelInicioLayout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel4)
                            .addGroup(jPanelInicioLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jComboBoxCentro, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(jPanelInicioLayout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(FechaDesde, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(28, 28, 28)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(FechaHasta, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(105, 105, 105)
                                .addComponent(ButtonBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 677, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanelInicioLayout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 616, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelInicioLayout.createSequentialGroup()
                        .addGap(294, 294, 294)
                        .addComponent(jButtonCancel)))
                .addContainerGap(259, Short.MAX_VALUE))
        );
        jPanelInicioLayout.setVerticalGroup(
            jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelInicioLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jComboBoxCentro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanelInicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(FechaDesde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ButtonBuscar)
                    .addComponent(jLabel3)
                    .addComponent(FechaHasta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(22, 22, 22)
                .addComponent(jButtonCancel))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanelInicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(56, 56, 56))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanelInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(216, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void ButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonBuscarActionPerformed
      String validarCamposObligatoriosMessage = validarCamposObligatorios(jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex()).toString(),
                   FechaDesde.getText(),
                   FechaHasta.getText());
            if ("".equals(validarCamposObligatoriosMessage)) {
                 buscarEventos();
            }else {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("CancelarEventos.CamposObligatorios") + validarCamposObligatoriosMessage);
        }
}//GEN-LAST:event_ButtonBuscarActionPerformed

    private void jComboBoxCentroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxCentroActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBoxCentroActionPerformed

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        System.out.print("Ha pulsado boton cancelar");
        CancelarEvento();
    }//GEN-LAST:event_jButtonCancelActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonBuscar;
    private javax.swing.JFormattedTextField FechaDesde;
    private javax.swing.JFormattedTextField FechaHasta;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JComboBox jComboBoxCentro;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    public static javax.swing.JPanel jPanelInicio;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
    private JPanel panelCentral;



      private void intialCharge() {
        try {
            //           try {
//            cargaCombo(jComboBoxCentro, "centrodocente");
        } catch (Exception ex) {
            Logger.getLogger(SS2_PantallaAltaEvento.class.getName()).log(Level.SEVERE, null, ex);
          }
    }

    private JComboBox carregaCombos(JComboBox jc, List l) {
        jc.removeAllItems();
        for (int i = 0; i < l.size(); i++) {
            jc.addItem(l.get(i));
        }
        return jc;
    }

   private void cargaCombo(JComboBox combo, String string) {
        List lista = null;
        System.out.println("Entro en CargaCombo para centros");
        try {
            if (string.equalsIgnoreCase("centrodocente")) {
                lista = objetoRemoto.dameListaCentros();
            } else if (false) {
            } else {
            }
            System.out.println("Lista" + lista.size());
        } catch (Exception ex) {
            Logger.getLogger(SS2_PantallaAltaEvento.class.getName()).log(Level.SEVERE, null, ex);
        }
        ComponentsUtils.cargaCombo(combo, lista);
    }
    private void buscarEventos() {
        try {
            System.out.print("Dentro de BuscarEventos 1: " + jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex()).toString());
            String validarCondicionesMessage = validarEventos();
            if ("".equals(validarCondicionesMessage)) {
                String v_CodigoCentro = "0";
                System.out.print("Dentro de BuscarEventos 2");
                KeyValue kv1 = (KeyValue) jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex());
                v_CodigoCentro = (String) kv1.getKey();
                System.out.print("Dentro de BuscarEventos 3: " + v_CodigoCentro.toString());
                //List<SS2_Evento> list = objetoRemoto.getListaEvento(kv1.toString(),
                try{
                List<SS2_Evento> list = objetoRemoto.getListaEvento(v_CodigoCentro,
                   FechaDesde.getText(),
                   FechaHasta.getText());
                System.out.print("Dentro de BuscarEventos 4");
                borrarElementosTabla();
                //Comprobamos que la consulta nos ha devuelto datos
                if (list.size() > 0) {
                    System.out.print("Dentro de BuscarEventos 5");
                    DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();
                    for (int i = 0; i < list.size(); i++) {
                        SS2_Evento eventos = list.get(i);
                        Object[] rowData = new Object[]{eventos.getfechaCelebracion(), eventos.getidEvento(), eventos.getNombre(), eventos.getCodCentro(), eventos.getduracion(), eventos.getCheckin() };
                        tm.insertRow(i, rowData);
                    }
                } else {
                    ExceptionUtils.visualizarInformacion(LanguageUtils.getMessage("CancelarEvento.NoDatos"));
                }
}
                catch (IllegalArgumentException ex) {
                   ExceptionUtils.visualizarInformacion(LanguageUtils.getMessage("SS3.error.formato.incorrecto"));
                   Logger.getLogger(SS2_PantallaCancelarEvento.class.getName()).log(Level.SEVERE, null, ex);
                } catch (FechasIncongruentesException ex) {
                   ExceptionUtils.visualizarInformacion(LanguageUtils.getMessage("SS3.error.formato.fecha.incongruentes"));
                   Logger.getLogger(SS2_PantallaCancelarEvento.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ParseException ex) {
                   ExceptionUtils.visualizarInformacion(LanguageUtils.getMessage("SS3.error.formato.fecha.incorrecta"));
                   Logger.getLogger(SS2_PantallaCancelarEvento.class.getName()).log(Level.SEVERE, null, ex);
                } catch (RemoteException ex) {
                   ExceptionUtils.visualizarError(LanguageUtils.getMessage("ERR_Remote"));
                   Logger.getLogger(SS2_PantallaCancelarEvento.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                ExceptionUtils.visualizarError(validarCondicionesMessage);
            }
        } catch (RemoteException ex) {
            ExceptionUtils.visualizarError(ExceptionUtils.ERR_Remote);
        } catch (Exception ex) {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("CancelarEvento.ERR_BuscarRegistros"));
        }
    }

    /*
     * Metodo que comprueba que se han introducido los campos obligatorios y el formato
     */
    private String validarEventos() throws RemoteException, Exception {
        //Validar que tiene un evento seleccionado
        KeyValue kv1 = (KeyValue) jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex());
        System.out.print(" ---kv1 : " +kv1);
        if (kv1 == null) {
            return LanguageUtils.getMessage("CancelarEvento.Errores.NoHayCentros");
        }
        return "";
    }

        private void borrarElementosTabla() {
        DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();
        if (tm != null && tm.getDataVector() != null) {
            tm.getDataVector().removeAllElements();
            jTable1.updateUI();
        }
    }

            /*
     * Metodo para rellenar el despegable de tipo de evento
     */
    private void setListCentrosToCombo(JComboBox combo) {
        try {
            List<SS1_CentroDocente> list = objetoRemoto.dameListaCentros();
            if (list != null && list.size() > 0) {
                for (SS1_CentroDocente CentroDocente : list) {
                    combo.addItem(new KeyValue(Integer.toString(CentroDocente.getId()), CentroDocente.getNombre()));
                }
            }
        } catch (RemoteException ex) {
            ExceptionUtils.visualizarError(ExceptionUtils.ERR_Remote);
        } catch (Exception ex) {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("CancelarEvento.ERR_Centros"));
        }
    }

     /*
    * Metodo que comprueba que se han introducido los campos obligatorios
    */

    private String validarCamposObligatorios(String centro, String FechaDesde,
            String FechaHasta) {

        System.out.println("Vamos a comprobar campos obligatorios");
        StringBuilder campos = new StringBuilder();
        try {
            if (centro == null || "".equals(centro)) {
                campos.append(LanguageUtils.getMessage("CancelarEventos.CampoObligatorio.Centro"));
            }
            if (FechaDesde == null || "".equals(FechaDesde)) {
                campos.append(LanguageUtils.getMessage("CancelarEventos.CampoObligatorio.FechaDesde"));
            }
            if (FechaHasta == null || "".equals(FechaHasta)) {
                campos.append(LanguageUtils.getMessage("CancelarEventos.CampoObligatorio.FechaHasta"));
            }


        } catch (Exception e) {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("AltaEventos.ERR_Validar"));
        }

        return campos.toString();
    }

    private void CancelarEvento() {
        try {
            String validarCondicionesMessage = validarInscripcion();
            if ("".equals(validarCondicionesMessage)) {
                List<SS2_Evento> lista = new ArrayList<SS2_Evento>();
                String v_CodigoCentro = "0";
                System.out.print("Dentro de CancelarEvento ");
                KeyValue kv1 = (KeyValue) jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex());
                v_CodigoCentro = (String) kv1.getKey();

                //Recorremos la tabla para guardar los cambios del CheckIn
                for (int a = 0; a < jTable1.getRowCount(); a++) {
                    
                    String v_Fecha = jTable1.getValueAt(a, 0).toString();
                    String vIdEvento = jTable1.getValueAt(a, 1).toString();
                    String v_Nombre = jTable1.getValueAt(a, 2).toString();
                    String v_Centro = jTable1.getValueAt(a, 3).toString();
                    String v_Duracion = jTable1.getValueAt(a, 4).toString();
                    Boolean v_Checkin = Boolean.parseBoolean(jTable1.getValueAt(a, 5).toString());
                   

                    System.out.println("Hemos seleccionado en la tabla: v_Fecha: " + v_Fecha
                                    + "v_Nombre: " + v_Nombre + "vIdEvento: " + vIdEvento +
                                    "v_Centro: " + v_Centro +
                                    "v_Duracion: " + v_Duracion +
                                    "v_Checkin: " + v_Checkin + "\n");
                     if(v_Checkin) {
                        System.out.println("LO CANCELAMOS");
                                       
                       SS2_Evento eventoCancelar = new SS2_Evento();

                       eventoCancelar.setidEvento(Integer.parseInt(vIdEvento));
                       eventoCancelar.setNombre(v_Nombre);
                       eventoCancelar.setCodCentro(Integer.parseInt(v_Centro));
                       lista.add(eventoCancelar);

                    }
                }

                //Comprobamos si hay elementos en la lista
                if (!lista.isEmpty()) {
                    if (objetoRemoto.CancelarEventos(lista)) {
                        ExceptionUtils.visualizarInformacion(LanguageUtils.getMessage("CancelarEvento.CancelarOk"));
                    } else {
                        ExceptionUtils.visualizarError(LanguageUtils.getMessage("CancelarEvento.ERR_Cancelar"));
                    }
                    borrarElementosTabla();
                }
            } else {
                ExceptionUtils.visualizarError(validarCondicionesMessage);
            }
        } catch (RemoteException ex) {
            ExceptionUtils.visualizarError(ExceptionUtils.ERR_Remote);
        } catch (Exception ex) {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("CancelarEvento.ERR_Cancelar"));
        }

    }

    /*
     * Metodo que comprueba que se han introducido los campos obligatorios y el formato
     */
    private String validarInscripcion() throws RemoteException, Exception {
        //Validar que tiene un evento seleccionado
        KeyValue kv1 = (KeyValue) jComboBoxCentro.getItemAt(jComboBoxCentro.getSelectedIndex());
        if (kv1 == null) {
            return LanguageUtils.getMessage("CancelarEvento.Errores.NoHayCentros");
        }
        return "";
    }

}

